import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ThemeChangePage extends StatefulWidget {
  const ThemeChangePage({super.key});

  @override
  State<ThemeChangePage> createState() => _ColorPickerScreenState();
}

class _ColorPickerScreenState extends State<ThemeChangePage> {
  Color _selectedColor = Colors.blue;
  final TextEditingController _hexController = TextEditingController();

  // 常用颜色列表
  final List<Color> _commonColors = [
    Colors.red,
    Colors.pink,
    Colors.purple,
    Colors.deepPurple,
    Colors.indigo,
    Colors.blue,
    Colors.lightBlue,
    Colors.cyan,
    Colors.teal,
    Colors.green,
    Colors.lightGreen,
    Colors.lime,
    Colors.yellow,
    Colors.amber,
    Colors.orange,
    Colors.deepOrange,
    Colors.brown,
    Colors.grey,
    Colors.blueGrey,
    const Color(0xFFFF000E),
  ];

  @override
  void initState() {
    super.initState();
    _hexController.text = _colorToHex(_selectedColor);
  }

  // 将颜色转换为十六进制字符串
  String _colorToHex(Color color) {
    return '#${color.value.toRadixString(16).padLeft(8, '0').substring(2)}';
  }

  // 从十六进制字符串解析颜色
  Color? _hexToColor(String hex) {
    try {
      hex = hex.replaceAll('#', '');
      if (hex.length == 6) hex = 'FF$hex'; // 添加透明度
      return Color(int.parse(hex, radix: 16));
    } catch (e) {
      return null;
    }
  }

  // 显示系统颜色选择器
  Future<void> _showSystemColorPicker() async {
    final Color? pickedColor = await showDialog<Color>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择颜色'),
        content: SingleChildScrollView(
          child: ColorPicker(
            pickerColor: _selectedColor,
            onColorChanged: (color) => _selectedColor = color,
            showLabel: true,
            pickerAreaHeightPercent: 0.7,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, _selectedColor),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (pickedColor != null) {
      setState(() {
        _selectedColor = pickedColor;
        _hexController.text = _colorToHex(pickedColor);
      });
    }
  }

  // 显示自定义颜色选择器
  void _showCustomColorPicker() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(20),
        child: ListView(
          children: [
            const Text(
              '选择颜色',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),

            // 常用颜色网格
            GridView.builder(
              shrinkWrap: true,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 6,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
              ),
              itemCount: _commonColors.length,
              itemBuilder: (context, index) {
                final color = _commonColors[index];
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectedColor = color;
                      _hexController.text = _colorToHex(color);
                    });
                    Navigator.pop(context);
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: color,
                      borderRadius: BorderRadius.circular(10),
                      border: _selectedColor == color
                          ? Border.all(color: Colors.white, width: 3)
                          : null,
                    ),
                    child: _selectedColor == color
                        ? const Icon(Icons.check, color: Colors.white)
                        : null,
                  ),
                );
              },
            ),

            const SizedBox(height: 20),
            const Divider(),
            const SizedBox(height: 10),

            // 十六进制颜色输入
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _hexController,
                    decoration: InputDecoration(
                      labelText: '十六进制颜色',
                      prefixText: '#',
                      border: const OutlineInputBorder(),
                      suffixIcon: IconButton(
                        icon: const Icon(Icons.paste),
                        onPressed: () async {
                          final clipboardData =
                              await Clipboard.getData('text/plain');
                          if (clipboardData != null &&
                              clipboardData.text != null) {
                            _hexController.text =
                                clipboardData.text!.replaceAll('#', '');
                          }
                        },
                      ),
                    ),
                    onChanged: (value) {
                      final color = _hexToColor(value);
                      if (color != null) {
                        setState(() => _selectedColor = color);
                      }
                    },
                  ),
                ),
                const SizedBox(width: 10),
                Container(
                  width: 50,
                  height: 50,
                  decoration: BoxDecoration(
                    color: _selectedColor,
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: Colors.grey),
                  ),
                ),
              ],
            ),

            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => Navigator.pop(context),
              style: ElevatedButton.styleFrom(
                backgroundColor: _selectedColor,
                foregroundColor: _selectedColor.computeLuminance() > 0.5
                    ? Colors.black
                    : Colors.white,
                minimumSize: const Size(double.infinity, 50),
              ),
              child: const Text('完成'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('颜色选择器'),
        backgroundColor: _selectedColor,
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 颜色预览
            Container(
              height: 150,
              width: double.infinity,
              decoration: BoxDecoration(
                color: _selectedColor,
                borderRadius: BorderRadius.circular(15),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10,
                    spreadRadius: 2,
                  )
                ],
              ),
              child: Center(
                child: Text(
                  _colorToHex(_selectedColor),
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: _selectedColor.computeLuminance() > 0.5
                        ? Colors.black
                        : Colors.white,
                  ),
                ),
              ),
            ),

            const SizedBox(height: 30),

            // 颜色信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _colorInfoItem('R', _selectedColor.red),
                _colorInfoItem('G', _selectedColor.green),
                _colorInfoItem('B', _selectedColor.blue),
                _colorInfoItem('A', _selectedColor.alpha),
              ],
            ),

            const SizedBox(height: 30),

            // 颜色选择按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // ElevatedButton.icon(
                //   onPressed: _showSystemColorPicker,
                //   icon: const Icon(Icons.colorize),
                //   label: const Text('系统选择器'),
                //   style: ElevatedButton.styleFrom(
                //     padding: const EdgeInsets.symmetric(
                //         horizontal: 20, vertical: 15),
                //   ),
                // ),
                ElevatedButton.icon(
                  onPressed: _showCustomColorPicker,
                  icon: const Icon(Icons.palette),
                  label: const Text('自定义选择器'),
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 20, vertical: 15),
                  ),
                ),
              ],
            ),

            const SizedBox(height: 30),

            // 使用示例
            const Text(
              '应用示例:',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: [
                Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: _selectedColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Text(
                    '按钮颜色',
                    style: TextStyle(color: _selectedColor),
                  ),
                ),
                ElevatedButton(
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _selectedColor,
                    foregroundColor: _selectedColor.computeLuminance() > 0.5
                        ? Colors.black
                        : Colors.white,
                  ),
                  child: const Text('示例按钮'),
                ),
                Chip(
                  label: const Text('标签'),
                  backgroundColor: _selectedColor.withOpacity(0.2),
                  labelStyle: TextStyle(color: _selectedColor),
                ),
                Icon(
                  Icons.favorite,
                  color: _selectedColor,
                  size: 30,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 颜色信息组件
  Widget _colorInfoItem(String label, int value) {
    return Column(
      children: [
        Text(
          label,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 5),
        Text(
          value.toString(),
          style: const TextStyle(fontSize: 18),
        ),
      ],
    );
  }
}

// 自定义颜色选择器组件
class ColorPicker extends StatefulWidget {
  final Color pickerColor;
  final ValueChanged<Color> onColorChanged;
  final bool showLabel;
  final double pickerAreaHeightPercent;

  const ColorPicker({
    super.key,
    required this.pickerColor,
    required this.onColorChanged,
    this.showLabel = true,
    this.pickerAreaHeightPercent = 0.7,
  });

  @override
  State<ColorPicker> createState() => _ColorPickerState();
}

class _ColorPickerState extends State<ColorPicker> {
  late HSVColor currentColor;

  @override
  void initState() {
    super.initState();
    currentColor = HSVColor.fromColor(widget.pickerColor);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: MediaQuery.of(context).size.height *
              widget.pickerAreaHeightPercent,
          child: Stack(
            children: [
              // 色相饱和度选择
              GestureDetector(
                onPanUpdate: _handlePanUpdate,
                onPanStart: _handlePanStart,
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    return CustomPaint(
                      painter: _HsvPainter(
                        hue: currentColor.hue,
                        saturation: currentColor.saturation,
                        value: currentColor.value,
                        width: constraints.maxWidth,
                        height: constraints.maxHeight,
                      ),
                    );
                  },
                ),
              ),

              // 选择器指示器
              Positioned(
                left: currentColor.saturation *
                        MediaQuery.of(context).size.width -
                    10,
                top: (1 - currentColor.value) *
                        MediaQuery.of(context).size.height *
                        widget.pickerAreaHeightPercent -
                    10,
                child: Container(
                  width: 20,
                  height: 20,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.white, width: 2),
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
              ),
            ],
          ),
        ),

        const SizedBox(height: 20),

        // 色相滑块
        Slider(
          value: currentColor.hue,
          min: 0,
          max: 360,
          divisions: 360,
          onChanged: (value) {
            setState(() {
              currentColor = currentColor.withHue(value);
              widget.onColorChanged(currentColor.toColor());
            });
          },
          activeColor: currentColor.toColor(),
        ),

        const SizedBox(height: 10),

        // 透明度滑块
        Slider(
          value: currentColor.alpha,
          min: 0,
          max: 1,
          divisions: 100,
          onChanged: (value) {
            setState(() {
              currentColor = currentColor.withAlpha(value);
              widget.onColorChanged(currentColor.toColor());
            });
          },
          activeColor: currentColor.toColor(),
        ),

        if (widget.showLabel) ...[
          const SizedBox(height: 20),
          Text(
            '当前颜色: ${_colorToHex(currentColor.toColor())}',
            style: const TextStyle(fontSize: 16),
          ),
        ],
      ],
    );
  }

  // 处理拖拽事件
  void _handlePanStart(DragStartDetails details) {
    _updateColor(details.localPosition);
  }

  void _handlePanUpdate(DragUpdateDetails details) {
    _updateColor(details.localPosition);
  }

  // 更新颜色
  void _updateColor(Offset position) {
    final width = MediaQuery.of(context).size.width;
    final height =
        MediaQuery.of(context).size.height * widget.pickerAreaHeightPercent;

    double saturation = (position.dx / width).clamp(0.0, 1.0);
    double value = 1 - (position.dy / height).clamp(0.0, 1.0);

    setState(() {
      currentColor = currentColor.withSaturation(saturation).withValue(value);
      widget.onColorChanged(currentColor.toColor());
    });
  }

  // 颜色转十六进制
  String _colorToHex(Color color) {
    return '#${color.value.toRadixString(16).padLeft(8, '0').substring(2)}';
  }
}

// HSV颜色选择器绘制
class _HsvPainter extends CustomPainter {
  final double hue;
  final double saturation;
  final double value;
  final double width;
  final double height;

  _HsvPainter({
    required this.hue,
    required this.saturation,
    required this.value,
    required this.width,
    required this.height,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Rect.fromLTWH(0, 0, width, height);

    // 绘制色相
    for (double x = 0; x < width; x++) {
      for (double y = 0; y < height; y++) {
        final s = x / width;
        final v = 1 - y / height;
        final color = HSVColor.fromAHSV(1.0, hue, s, v).toColor();
        final paint = Paint()..color = color;
        canvas.drawRect(Rect.fromLTWH(x, y, 1, 1), paint);
      }
    }

    // 绘制边框
    final borderPaint = Paint()
      ..color = Colors.grey
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    canvas.drawRect(rect, borderPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
